<template>
  <div class="app-container">
    <div style="font-size: 25px;">库间调拨单</div>
    <el-divider></el-divider>
    <div>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="调拨单号" prop="allocationOrder" style="width: 400px">
              <el-input v-model="allocationOrder" placeholder="请输入调拨单号" oninput="value=value.replace(/[^\d\w]/g,'')" maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库仓库" prop="lssueWarehouse" style="width: 400px">
              <el-select
                v-model="form.lssueWarehouse"
                placeholder="请选择出库仓库"
                clearable
                size="medium"
                style="width: 320px"
              >
                <el-option
                  v-for="dict in warehouseList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库仓库" prop="warehousingId" style="width: 400px">
              <el-select
                v-model="form.warehousingId"
                placeholder="请选择入库仓库"
                clearable
                size="medium"
                style="width: 320px"
                @change="check"
              >
                <el-option
                  v-for="dict in warehouseList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作人" prop="creatUser" style="width: 400px">
              <el-input v-model="form.creatUser" placeholder="请输入操作人" maxlegth="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark" style="width: 400px">
              <el-input v-model="form.remark" placeholder="请输入备注" maxlegth="250"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row style="margin-bottom: 20px;">
          <el-col :span="1.5">
            <div style="font-size: 20px; margin-top: 5px">调拨商品</div>
          </el-col>
          <el-col :span="5">
            <el-button type="primary" @click="handleAdd" style="margin-left: 20px;">点击添加商品</el-button>
          </el-col>
        </el-row>
        <div style="margin-top:10px;">
          <el-table :data="addGoodsList">
            <el-table-column label="商品ID" align="center" prop="goodId"/>
            <el-table-column label="商品名称" align="center" prop="goodName"/>
            <el-table-column label="仓库名称" align="center" prop="warehouseName"/>
            <el-table-column label="分类" align="center" prop="categoryName"/>
            <el-table-column label="品牌" align="center" prop="brandName"/>
            <el-table-column label="单位" align="center" prop="companyName"/>
            <el-table-column label="仓库库存" align="center" prop="stock"/>
            <el-table-column label="调拨数量" align="center" prop="goodNumber">
              <div class="item" slot-scope="scope">
                <el-input-number v-model="scope.row.goodNumber" controls-position="right"
                                 oninput="value=value.replace(/[^0-9.]/g,'')" :min="1" size="mini" style="width:100px"
                />
              </div>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-error"
                  @click="deleteGoodsList(scope.row)"
                >删除商品
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>

    <!-- 添加或修改销售订单对话框 -->
    <el-dialog :title="title" :close-on-click-modal = "false"  :visible.sync="open" width="1500px" append-to-body>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入商品名称"
            clearable
            maxlength="35"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select
            v-model="queryParams.brandId"
            placeholder="请选择品牌"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          >
            <el-option
              v-for="dict in brandList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="上下架" prop="shelves">
          <el-select
            v-model="queryParams.shelves"
            placeholder="请输入上下架"
            clearable
            @keyup.enter.native="handleQuery"
          >
            <el-option label="上架" value=1 />
            <el-option label="下架" value=0 />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <treeselect v-model="queryParams.categoryId" :options="categoryOptions" :normalizer="normalizer"
                      placeholder="选择分类"
                      style="width: 230px;"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="goodsList">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="商品ID" align="center" prop="id"/>
        <el-table-column label="商品名称" align="center" prop="name"/>
        <el-table-column label="仓库名称" align="center" prop="warehouseName"/>
        <el-table-column label="分类" align="center" prop="categoryName"/>
        <el-table-column label="品牌" align="center" prop="brandName"/>
        <el-table-column label="单位" align="center" prop="companyName"/>
        <el-table-column label="仓库库存" align="center" prop="inventory"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-circle-plus-outline"
              @click="addGood(scope.row)"
            >添加商品
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getGoodList"
      />
      <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
        <el-button @click="cancelGoods">关闭页面</el-button>
      </div>
    </el-dialog>

    <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 50px;">
      <el-button type="primary" @click="submitForm">保存调拨单</el-button>
    </div>
  </div>


</template>

<script>

import {regionData} from "element-china-area-data";
import {warehouseList} from "@/api/erp/goods";
import {listCategory} from "@/api/erp/category";
import {listBrand} from "@/api/erp/brand";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listWarehouse} from "@/api/erp/warehouse";
import {addAllocation, getAllocation, updateAllocation} from "@/api/erp/allocation";

let stream = require('stream')

export default {
  name: "sale",
  components: {Treeselect},
  dicts: ['erp_payment_type'],
  data() {
    return {
      //仓库List
      warehouseList: [],
      //调拨单号
      allocationOrder: null,
      //销售单号
      saleOrderNum: null,
      //品牌列表
      brandList: [],
      //elementUi地区数据
      options: regionData,
      //分类列表
      categoryOptions: [],
      //客户列表
      customerList: [],
      //客户电话
      customerTelephone: null,
      //客户地址
      detailedAdd: null,
      // 商品信息表格数据
      goodsList: [],
      // 添加的商品信息表格数据
      addGoodsList: [],
      //客户省市区
      selectedOptions: [],
      // 总条数
      total: 0,
      //表单参数
      form: {},
      //商品表单参数
      goodsForm: {},
      // 显示搜索条件
      showSearch: true,
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //表单校验
      rules: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        brandId: null,
        categoryId: null,
        type: null,
        labels: null,
        barCode: null,
        warehouseId: null,
      },
    };
  },
  created() {
    //查询仓库list
    this.getWarehouse();
    const allocationId = this.$route.query.id
    //获取调拨单信息
    this.getAllocationById(allocationId);
  },

  methods: {
    //保存销售订单提交按钮
    submitForm() {
      var allocationGoods = this.addGoodsList
      this.form.erpAllocationGoods = allocationGoods;
      this.form.allocationOrder = this.allocationOrder
      updateAllocation(this.form).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("修改成功");
          this.close();
        }
      });
    },

    getAllocationById(id){
      getAllocation(id).then(res =>{
        this.form = res.data
        this.allocationOrder = res.data.allocationOrder
        this.addGoodsList = res.data.erpAllocationGoods
      })
    },

    //添加商品方法
    addGood(row) {
      for (var i = 0; i < this.addGoodsList.length; i++) {
        let newVar = this.addGoodsList[i];
        if (row.id === newVar.goodId) {
          this.$modal.msgWarning("以添加过此商品!");
          return;
        }
      }
      if (row.inventory <= 0) {
        this.$modal.msgWarning("商品库存不足!");
        return;
      }
      row.stock = row.inventory
      row.goodId = row.id
      row.goodName = row.name
      this.addGoodsList.push(row);
    },

    //删除添加的商品方法
    deleteGoodsList(row) {
      this.addGoodsList.splice(this.addGoodsList.indexOf(row), 1);
    },
    //新增商品按钮操作
    handleAdd() {
      if (this.form.lssueWarehouse == null) {
        this.$modal.msgWarning("请完善基础信息!");
        return;
      }
      this.getBrandList();
      this.getCategoryList();
      this.getGoodList();
      this.open = true;
      this.title = "添加商品";
    },
    //查询商品列表
    getGoodList() {
      this.loading = true;
      this.queryParams.warehouseId = this.form.lssueWarehouse
      warehouseList(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    check() {
      if (this.form.lssueWarehouse == this.form.warehousingId) {
        this.$modal.msgWarning("入库仓库不能与出库仓库相同!");
        this.form.warehousingId = null;
        return;
      }
    },
    /*查询仓库*/
    getWarehouse() {
      listWarehouse().then(response => {
        this.warehouseList = response.rows;
      });
    },

    //获取分类列表
    getCategoryList() {
      let params = {};
      listCategory(params).then(response => {
        this.categoryOptions = this.handleTree(response.data, "id", "parentId");
      });
    },
    //node分类节点
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    //查询品牌列表
    getBrandList() {
      let params = {};
      listBrand(params).then(response => {
        this.brandList = response.rows;
      });
    },
    //搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getGoodList();
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //返回上一页商品列表页
    close() {
      this.$router.go(-1);
    },

    //关闭弹出框
    cancelGoods() {
      this.open = false;
    }

  }
}

</script>

